package repositories

import (
	"MyWeb/internal/global"
	"MyWeb/internal/models"
	"errors"
	"gorm.io/gorm"
	"time"
)

type UrlMapRepoUse struct {
	Db *gorm.DB
}

// NewUrlMapRepoUse 加载全局DB
func NewUrlMapRepoUse() *UrlMapRepoUse {
	return &UrlMapRepoUse{
		Db: global.Db,
	}
}

func (u *UrlMapRepoUse) CreateSHortURL(url *models.UrlMap) error {
	err := u.Db.Create(&url).Error
	if err != nil {
		return errors.New("数据库插入失败")
	}
	return nil
}

func (u *UrlMapRepoUse) FindShortURL(UserShortURL string) error {
	var url models.UrlMap
	u.Db.Select("short_url").Where("short_url = ?", UserShortURL).First(&url)
	if url.ShortUrl != "" {
		return errors.New("该短链已存在！")
	}
	return nil
}

func (u *UrlMapRepoUse) FindLongURL(ShortURL string) (*models.UrlMap, error) {
	var url models.UrlMap
	u.Db.Select("*").Where("short_url = ?", ShortURL).First(&url)
	if u.IsExpiredAt(&url) {
		if url.LongUrl != "" {
			return &url, nil
		}
		return nil, errors.New("数据库不存在该短链")
	} else {
		return nil, errors.New("该短链已失效")
	}
}

func (u *UrlMapRepoUse) IsExpiredAt(url *models.UrlMap) bool {
	if time.Now().Before(url.ExpiresAt) { //now <= expired
		//fmt.Println("不超时")
		return true
	} else {
		//fmt.Println("超时")
		return false
	}
}
